package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private WxMaService wxMaService;

	@Autowired
	private KafkaService kafkaService;

	@Autowired
	private RedisTemplate redisTemplate;


	@Override
	public Map<String, String> wxLogin(String code) {
		try {
			//获取微信唯一id标识
			WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
			String wxOpenId = sessionInfo.getOpenid();

			//判断用户是否为第一次登陆
			LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper();
			lambdaQueryWrapper.eq(UserInfo::getWxOpenId,wxOpenId);
			UserInfo userInfo = userInfoMapper.selectOne(lambdaQueryWrapper);
			//判断用户信息是否为空
			if(userInfo==null){
				//保存用户信息记录以及初始化账户余额
				userInfo = new UserInfo();
				userInfo.setNickname("听友"+ IdUtil.getSnowflakeNextId());
				userInfo.setWxOpenId(wxOpenId);
				userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
				userInfo.setIsVip(0);
				userInfo.setVipExpireTime(null);
				userInfoMapper.insert(userInfo);
				kafkaService.sendKafkaMessage(KafkaConstant.QUEUE_USER_REGISTER,userInfo.getId().toString());
			}
			//4.产生登录令牌（自定义登陆态）基于用户信息跟token进行关联
			//4.1 生成自定义token令牌

			String token = IdUtil.randomUUID();
			//4.2 构建登录key 形式：user:login:token
			String key = RedisConstant.USER_LOGIN_KEY_PREFIX+ token;
			//4.3 将token作为Key 将用户信息UserInfoVo作为Value写入Redis
			UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);
			redisTemplate.opsForValue().set(key,userInfoVo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
			//5.封装登录结果
			Map<String,String> map = new HashMap<>();
			map.put("token",token);
			return map;
		} catch (WxErrorException e) {
			throw new RuntimeException(e);
		}
	}


	@Override
	public UserInfoVo getUserInfo(Long userId) {
		UserInfo userInfo = userInfoMapper.selectById(userId);
		UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);
		return userInfoVo;
	}


	@Override
	public void updateUser(Long userId, UserInfoVo userInfoVo) {
		UserInfo userInfo = new UserInfo();
		userInfo.setId(userId);
		userInfo.setNickname(userInfoVo.getNickname());
		userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
		userInfoMapper.updateById(userInfo);
	}

}
